<template>
  <el-dialog :visible="isShow" width="600px" class="register" :show-close="false">
    <div class="title" slot="title">用户注册</div>
    <el-form ref="form" :rules="rules" :model="form" label-width="70px">
      <el-form-item label="头像" prop="avatar">
        <el-upload
          name="image"
          class="avatar-uploader"
          :action="baseUrl + '/uploads'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code">
        <el-row>
          <el-col :span="16" class="col">
            <el-input v-model="form.code" placeholder="请输入图形码"></el-input>
          </el-col>
          <el-col :span="6">
            <img @click="refreshCode" class="code" :src="codeUrl" alt />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="16" class="col">
            <el-input v-model="form.rcode" placeholder="请输入验证码"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button @click="getRcode" :disabled="totalTime != 60">
              获取验证码
              <span v-if="totalTime < 60">{{ totalTime }}s</span>
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div class="footer" slot="footer">
      <el-button @click="isShow = false">取消</el-button>
      <el-button @click="goRegister" type="primary">注册</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { sendsms, register } from "@/api/register.js";
export default {
  data() {
    return {
      totalTime: 60, // 验证码倒计时
      codeUrl: process.env.VUE_APP_URL + "/captcha?type=sendsms", // 验证码路径地址
      baseUrl: process.env.VUE_APP_URL, // 基地址
      imageUrl: "", // 头像路径地址
      isShow: false, // 注册框显示
      captcha: "", // 接口返回的验证码
      form: {
        avatar: "", // 头像
        username: "", // 昵称
        email: "", // 邮箱
        phone: "", // 手机号
        password: "", // 密码
        code: "", // 图形码
        rcode: "" // 验证码
      },
      rules: {
        avatar: [{ required: true, message: "请添加头像", trigger: "change" }],
        username: [
          { required: true, message: "请输入昵称", trigger: "change" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (reg.test(value)) {
                callback();
              } else {
                callback("请正确填写邮箱");
              }
            }
          }
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback("请正确填写手机号");
              }
            }
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" }
        ],
        code: [{ required: true, message: "请输入图形码", trigger: "change" }],
        rcode: [
          { required: true, message: "请输入验证码", trigger: "change" },
          {
            validator: (rule, val, callback) => {
              if (val == this.captcha) {
                callback();
              } else {
                callback("验证码错误");
              }
            }
          }
        ]
      }
    };
  },
  watch: {
    isShow(newVal) {
      if (newVal == false) {
        this.$refs.form.resetFields();
        this.imageUrl = "";
      }
    }
  },
  methods: {
    // 注册
    goRegister() {
      this.$refs.form.validate(result => {
        if (!result) {
          this.$message.warning("都是必填项噢");
        } else {
          register(this.form).then(() => {
            this.$message.success("注册成功");
            this.isShow = false;
          });
        }
      });
    },
    // 刷新注册图形码
    refreshCode() {
      this.codeUrl =
        process.env.VUE_APP_URL + "/captcha?type=sendsms&random=" + Date.now();
    },
    // 获取验证码
    getRcode() {
      let count = 0; // 正确次数
      this.$refs.form.validateField(["phone", "code"], err => {
        if (!err) {
          count++;
        }
        if (count == 2) {
          this.totalTime--;
          let timeId = setInterval(() => {
            this.totalTime--;
            if (this.totalTime <= 0) {
              this.totalTime = 60;
              clearInterval(timeId);
            }
          }, 1000);
          sendsms({
            code: this.form.code,
            phone: this.form.phone
          }).then(res => {
            if (res.code === 200) {
              this.$message.success(res.data.captcha + ""); // 传递字符串不是数字
              this.captcha = res.data.captcha;
            } else {
              this.form.code = "";
              this.$message.error(res.message);
              this.refreshCode();
            }
          });
        }
      });
    },
    // 头像
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      let arr = ["image/jpeg", "image/png"];
      const isJPG = arr.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG和PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style lang="less">
.register {
  .el-dialog__header {
    padding: 0;
  }
  .el-dialog__body {
    padding: 26px;
  }
  .footer {
    text-align: center;
  }
  .code {
    display: block;
    width: 140px;
    height: 40px;
  }
  .col {
    margin-right: 21px;
  }
  .title {
    height: 53px;
    text-align: center;
    line-height: 53px;
    background: linear-gradient(to right, #01c5fa, #1395fa);
  }
  .el-form-item__label {
    text-align: center;
  }
  .avatar-uploader {
    text-align: center;
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>
